using SomniumSpace.Bridge;
using System;
using UnityEngine;
using UnityEngine.Events;

namespace TheCloud
{
    /// <summary>
    /// Detect somnium spcac player CharacterController, usufull for player detection
    /// </summary>
    public class LocalPlayerTrigger : MonoBehaviour
    {
        public event Action<CharacterController> OnPlayerEnter;
        public event Action<CharacterController> OnPlayerExit;

        [Header("Events")]
        [SerializeField] UnityEvent<CharacterController> _onPlayerEnter;
        [SerializeField] UnityEvent<CharacterController> _onPlayerExit;

        private GameObject _localPlayerBody = null;
        private CharacterController _localCharacterController = null;

        private void Start()
        {
            if(!Application.isEditor)
                SomniumBridge.Network.OnJoinedToGameSession += GetLocalPlayer;
        }

        private void GetLocalPlayer()
        {
            Transform bodyTr = SomniumBridge.PlayersContainer?.LocalPlayer?.References?.Body?.Root;

            if (bodyTr == null)
            {
                Debug.LogError($"[{nameof(LocalPlayerTrigger)}] Can't find Local Player Body");
                return;
            }

            _localPlayerBody = bodyTr.gameObject;

            if (_localPlayerBody == null)
            {
                Debug.LogError($"[{nameof(LocalPlayerTrigger)}] Can't find Local Player Body CharacterController");
                return;
            }
            
            _localCharacterController = _localPlayerBody.GetComponent<CharacterController>();
        }

        private void OnTriggerEnter(Collider other)
        {
            if (_localPlayerBody == null)
            {
                Debug.LogError($"[{nameof(LocalPlayerTrigger)}] _localPlayerBody is null");
                return;
            }

            if (_localPlayerBody == other.gameObject)
            {
                //Debug.Log($"[{nameof(CharacterTrigger)}] OnTriggerEnter: {other.name}");
                OnPlayerEnter?.Invoke(_localCharacterController);
                _onPlayerEnter?.Invoke(_localCharacterController);
            }
        }

        private void OnTriggerExit(Collider other)
        {
            if (_localPlayerBody == null)
            {
                Debug.LogError($"[{nameof(LocalPlayerTrigger)}] _localPlayerBody is null");
                return;
            }

            if (_localPlayerBody == other.gameObject)
            {
                //Debug.Log($"[{nameof(CharacterTrigger)}] OnTriggerEnter: {other.name}");
                OnPlayerExit?.Invoke(_localCharacterController);
                _onPlayerExit?.Invoke(_localCharacterController);
            }
        }
    }
}
